package com.pet.customer.controller;

import com.pet.customer.mapper.AccountMapper;
import com.pet.customer.mapper.OrdersMapper;
import com.pet.customer.mapper.ShopMapper;
import com.pet.customer.model.Account;
import com.pet.customer.model.AccountExample;
import com.pet.customer.model.Orders;
import com.pet.customer.model.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;


@RestController
public class OrdersController {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ShopMapper shopMapper;

    @RequestMapping(value="/cancelOrders",method = RequestMethod.POST)
    public String cancelOrders(HttpServletRequest request, Model model) throws ParseException {
        String id = request.getParameter("id");
        Orders orders = ordersMapper.selectByPrimaryKey(Integer.parseInt(id));
        orders.setStatus("CANCELED");
        ordersMapper.updateByPrimaryKeySelective(orders);
        return "OK";
    }

    @RequestMapping(value="/confirmOrders",method = RequestMethod.POST)
    public String confirmOrders(HttpServletRequest request, Model model) throws ParseException {
        String id = request.getParameter("id");
        Orders orders = ordersMapper.selectByPrimaryKey(Integer.parseInt(id));
        orders.setStatus("CONFIRMED");
        ordersMapper.updateByPrimaryKeySelective(orders);
        String price = orders.getPrice();
        int shopId = orders.getShopid();
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        String sellerEmail =  shop.getEmail();
        AccountExample accountExample = new AccountExample();
        accountExample.createCriteria().andEmailEqualTo(sellerEmail);
        List<Account> accountList = accountMapper.selectByExample(accountExample);
        if(accountList.size()>0){
            Account account = accountList.get(0);
            account.setTotal(account.getTotal()+Double.parseDouble(price.trim().substring(1)));
            accountMapper.updateByPrimaryKeySelective(account);
        }
        return "OK";
    }

}